<?php
namespace app\customer\controller;
require_once '../extend/lib/WxPayDataBase.php';
use think\Db;
use lib\WxPayApi;
use lib\WxPayException;
use lib\WxPayConfigInterface;
use lib\WxPayDataBase;
use lib\WxPayUnifiedOrder;
use lib\WxPayRefund;
use lib\WxPayRefundQuery;
use lib\WxPayNotify;
use lib\WxPayConfig;
use lib\WeixinPay;
class Pluginshop extends Base{
    //标题设置
    public function titleset(){
        if(request()->isGet()){
            $data=Db::name('aboutus')->where('cus_id',session('customer')['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            $data['shopindextitle']=$param['shopindextitle'];
            $data['shopcatetitle']=$param['shopcatetitle'];
            $data['shopcarttitle']=$param['shopcarttitle'];
            $data['shopmytitle']=$param['shopmytitle'];
            $data['shopsearchtitle']=$param['shopsearchtitle'];
            $data['shopmyordertitle']=$param['shopmyordertitle'];
            $data['shopdetailtitle']=$param['shopdetailtitle'];
            $data['shopcollecttitle']=$param['shopcollecttitle'];
            $data['shopevaluatetitle']=$param['shopevaluatetitle'];
            $data['shopmyaddresstitle']=$param['shopmyaddresstitle'];
            $data['shopaddaddresstitle']=$param['shopaddaddresstitle'];
            $data['shopeditaddresstitle']=$param['shopeditaddresstitle'];
            $res= Db::name('aboutus')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200,'msg' => '更新成功']);
            }else{
                $cus=Db::name('aboutus')->where('cus_id',session('customer')['id'])->find();
                if($cus){
                    return json(['code' => 500,'msg' => '失败']);
                }else{
                    $resin= Db::name('aboutus')->insert($data);
                    if($resin){
                        return json(['code' => 200,'msg' => '保存成功']);
                    }else{
                        return json(['code' => 500,'msg' => '失败']);
                    }
                }
            }
        }
    }
    //小程序设置
    public function payset(){
        if(request()->isGet()){
            $data=Db::name('aboutus')->where('cus_id',session('customer')['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $certfile ="./cert/" . 'apiclient_cert_' .session('customer')['id']. '.pem';
            $keyfile ="./cert/" . 'apiclient_key_' .session('customer')['id']. '.pem';
            $param = input('post.');
            $data['cus_id']=session('customer')['id'];
            if($param['apiclient_cert']){
                file_put_contents($certfile, trim($param['apiclient_cert']));
                $data['apiclient_cert']=$param['apiclient_cert'];
            }
            if($param['apiclient_key']){
                 file_put_contents($keyfile, trim($param['apiclient_key']));
                $data['apiclient_key']=$param['apiclient_key']; 
            }
            $data['mac_id']=$param['mac_id'];
            $data['apikey']=$param['apikey'];
            $data['shopstate']=$param['shopstate'];
            $res= Db::name('aboutus')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200,'msg' => '更新成功']);
            }else{
                $cus=Db::name('aboutus')->where('cus_id',session('customer')['id'])->find();
                if($cus){
                    return json(['code' => 500,'msg' => '失败']);
                }else{
                    $resin= Db::name('aboutus')->insert($data);
                    if($resin){
                        return json(['code' => 200,'msg' => '保存成功']);
                    }else{
                        return json(['code' => 500,'msg' => '失败']);
                    }
                }
            }
        }
    }
    //其他设置
    public function otherset(){
        if(request()->isGet()){
            $data=Db::name('customer')->where('id',session('customer')['id'])->find();
            $this->assign('data',$data);
            return $this->fetch();
        }elseif(request()->isPost()){
            $param = input('post.');
            $data['freeexpressfee']=$param['freeexpressfee'];
            $data['expressfee']=$param['expressfee'];
            $data['expressfeestate']=$param['expressfeestate'];
            $data['email_state']=$param['email_state'];
            $data['email_self']=$param['email_self'];
            $data['email_code']=$param['email_code'];
            $data['flagcontent']=$param['flagcontent'];
            $data['servershop']=$param['servershop'];
            $data['flags']=$param['flags'];
            $data['flagtitle']=$param['flagtitle'];
            $res= Db::name('customer')->where(array('id'=>$param['id']))->update($data);
            if($res){
                return json(['code' => 200,'msg' => '更新成功']);
            }else{
                $cus=Db::name('customer')->where('id',session('customer')['id'])->find();
                if($cus){
                    return json(['code' => 500,'msg' => '失败']);
                }else{
                    $resin= Db::name('customer')->insert($data);
                    if($resin){
                        return json(['code' => 200,'msg' => '保存成功']);
                    }else{
                        return json(['code' => 500,'msg' => '失败']);
                    }
                }
            }
        }
    }
    public function orders_list(){
        $key=input('get.key');
        if (!empty(input('get.fromtime'))) {
            $fromtime=strtotime(input('get.fromtime'));
        }else{
            $fromtime=0;
        }
        if (!empty(input('get.totime'))) {
            $totime=strtotime(input('get.totime'))+86400;
        }else{
            $totime=time();
        }
        $list=Db::name('orders')->alias('a')->join('shopgoods b', 'a.p_id = b.id','LEFT')->join('address c', 'a.address_id = c.id','LEFT')->field('a.*,b.title,c.uname,c.uphone,c.uaddress')->where('a.cus_id',session('customer')['id'])->where('a.time','>',"{$fromtime}")->where('a.time','<',"{$totime}")->where('a.paycode|b.title|c.uname|c.uphone|c.uaddress','like',"%{$key}%")->order('a.id desc')->paginate(10);
        $lists=Db::name('orders')->alias('a')->join('shopgoods b', 'a.p_id = b.id','LEFT')->join('address c', 'a.address_id = c.id','LEFT')->field('a.*,b.title,c.uname,c.uphone,c.uaddress')->where('a.cus_id',session('customer')['id'])->where('a.time','>',"{$fromtime}")->where('a.time','<',"{$totime}")->where('a.paycode|b.title|c.uname|c.uphone|c.uaddress','like',"%{$key}%")->select();
        $data=$list->all();
        $this->assign('key',input('get.key'));
        $this->assign('fromtime',input('get.fromtime'));
        $this->assign('totime',input('get.totime'));
        $this->assign('data',$data);
        $this->assign('list',$list);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    public function orderdetail(){
        if(request()->isGet()){
            $param = input('get.');
            $list=Db::name('orders')->alias('a')->join('shopgoods b', 'a.p_id = b.id','LEFT')->join('address c', 'a.address_id = c.id','LEFT')->field('a.*,b.title,c.uname,c.uphone,c.uaddress')->where('a.id',$param['id'])->find();
            $this->assign('list',$list);
            $lists=Db::name('ordersub')->alias('a')->join('shopgoods b', 'a.p_id = b.id','LEFT')->join('address c', 'a.address_id = c.id','LEFT')->field('a.*,b.title,c.uname,c.uphone,c.uaddress')->where('a.of_id',$param['id'])->select();
            $this->assign('list',$list);
            $this->assign('lists',$lists);
            return $this->fetch();
        }
    }
    public function applyrefuse(){
        $id=input('param.id');
        $status = Db::name('orders')->where('id',$id)->update(['salesbacktate'=>3]);
        if($status){
            Db::name('ordersub')->where('of_id',$id)->update(['salesbacktate'=>3]);
            return json(['code' => 200,'msg' => '成功']);
        }else{
            return json(['code' => 500,'msg' => '失败']);
        }
    }
    public function refusepayfee(){
        $id=input('param.id');
        $paystate = Db::name('orders')->where('id',$id)->find();
        if($paystate['paystate']==2||$paystate['paystate']==7){
            $aboutus=Db::name('aboutus')->where('cus_id',$paystate['cus_id'])->find();
            $sslCertPath ="./cert/" . 'apiclient_cert_' .$paystate['cus_id']. '.pem';
            $sslKeyPath ="./cert/" . 'apiclient_key_' .$paystate['cus_id']. '.pem';
            $key=$aboutus['apikey'];
            $input = new WxPayRefund();
            $WxPayApi = new WxPayApi();
            $config = new WxPayUnifiedOrder();
            $config->SetAppid($aboutus['appid']);
            $config->SetMch_id($aboutus['mac_id']);
            $config->SetMerchantId($aboutus['mac_id']);
            $config->SetSignType('MD5');
            $config->SetKey($key);
            $config->SetSSLCertPath($sslCertPath, $sslKeyPath);
            $config->SetReportLevenl(1);

            $input->SetAppid($aboutus['appid']);
            $input->SetMch_id($aboutus['mac_id']);
            // $input->SetOp_user_id($aboutus['mac_id']);
            $input->SetRefund_fee(floatval($paystate['payfee']*100));
            $input->SetTotal_fee(floatval($paystate['payfee']*100));
            $input->SetOut_refund_no($paystate['paycode']);
            $input->SetOut_trade_no($paystate['paycode']);
            // $result = $WxPayApi->refund($input, 6, $path_cert, $path_key, $key);
            $result = $WxPayApi->refund($config,$input);

            if ($result['result_code'] == 'SUCCESS') {//退款成功
                $status = Db::name('orders')->where('id',$id)->update(['paystate'=>5,'salesbacktate'=>5]);
                if($status){
                    Db::name('ordersub')->where('of_id',$id)->update(['paystate'=>5,'salesbacktate'=>5]);
                    return json(['code' => 200,'msg' => '成功']);
                }else{
                    return json(['code' => 500,'msg' => '失败']);
                }
            }else{
                return json(['code' => 502,'msg' => '退款失败']);
            }
        }else{
            return json(['code' => 501,'msg' => '支付状态不对']);
        }
    }
    // public function timeouts(){
    //     $param = input('param.');
    //     $ntime=time();
    //     for($i=0;$i<count($param['ids']);$i++){
    //         $times[$i]=Db::name('orders')->where('id',$param['ids'][$i])->find();
    //         $goid[$i]=$times[$i]['id'];
    //         if($ntime < $times[$i]['etime']){
    //             $retime[$i] = $times[$i]['etime']-$ntime;
    //             $reday[$i] = floor($retime[$i]/(60*60*24));
    //             $rehour[$i] = floor($retime[$i]/(60*60));
    //             $rehours[$i] = floor($rehour[$i]-$reday[$i]*24);
    //             $reminute[$i] = floor(($retime[$i] - $rehour[$i]*60*60)/60);
    //             $resecond[$i] = ($retime[$i] - $rehour[$i]*60*60 - $reminute[$i]*60); //剩余的秒数
    //         }else{
    //             $jieguo=Db::name('orders')->where('id',$goid[$i])->update(['paystate'=>4]);
    //             if ($jieguo) {
    //                 $cus=Db::name('orders')->where('id',$goid[$i])->find();
    //                 return json(['code' => 201,'msg' => '更改成功']);
    //             }
    //             return json(['code' => 500,'msg' => '失败']);
    //         }
    //     }
    //     return json(['code' => 200,'msg' => '获取成功','goid'=>$goid,'reday'=>$reday,'rehours'=>$rehours,'reminute'=>$reminute,'resecond'=>$resecond]);
    // }
    public function timeoutstate(){
        $id = input('param.id');
        $jieguo=Db::name('orders')->where('id',$id)->update(['paystate'=>4]);
        if ($jieguo) {
            return json(['code' => 200,'msg' => '成功']);
        }
        return json(['code' => 500,'msg' => '失败']);
    }
    public function expressinfo(){
        $param = input('param.');
        $data['express']=$param['express'];
        $data['expressnum']=$param['expressnum'];
        $data['paystate']=3;
        $data['uptime']=time();
        $data['etime']=time()+86400*7;
        $res=Db::name('orders')->where('id',$param['order_id'])->update($data);
        if($res){
            return json(['code' => 200,'msg' => '成功']);
        }else{
            return json(['code' => 500,'msg' => '失败']);
        }
    }
}
